<template>
  <div class="device-query-overlay" v-if="visible" @click.self="closeDeviceQuery">
    <div class="device-query-modal">
      <div class="device-query-header">
        <h3>设备使用情况查询</h3>
        <button class="close-btn" @click="closeDeviceQuery">×</button>
      </div>
      
      <div class="device-query-content">
        <!-- 甘特图头部：时间轴 -->
        <div class="gantt-header">
          <div class="gantt-time-axis">
            <div class="time-label-header">
              <div class="header-title">时间/设备</div>
            </div>
            <div class="time-labels" ref="timeLabels" @scroll="onTimeLabelsScroll">
              <div 
                v-for="timeSlot in timeSlots" 
                :key="timeSlot.index"
                class="time-label"
              >
                {{ formatTimeSlot(timeSlot) }}
              </div>
            </div>
          </div>
        </div>

        <!-- 甘特图主体 -->
        <div class="gantt-body">
          <div class="gantt-devices">
            <!-- 设备列表（左侧） -->
            <div class="device-labels">
              <div 
                v-for="device in allDevices" 
                :key="device.name"
                class="device-label"
              >
                {{ device.name }}
              </div>
            </div>

            <!-- 设备使用情况网格 -->
            <div class="satellite-grid" ref="satelliteGrid" @scroll="onSatelliteGridScroll">
              <div 
                v-for="device in allDevices" 
                :key="device.name"
                class="device-row"
              >
                <div 
                  v-for="timeSlot in timeSlots" 
                  :key="`${device.name}-${timeSlot.index}`"
                  class="satellite-cell"
                  :class="getSatelliteCellClass(device.name, timeSlot.index)"
                  :title="getSatelliteCellTooltip(device.name, timeSlot.index)"
                >
                  <div class="satellite-info">
                    <div 
                      v-for="satellite in getSatellitesUsingDevice(device.name, timeSlot.index)" 
                      :key="satellite.name"
                      class="satellite-item"
                      :style="{ backgroundColor: satellite.color }"
                    >
                      <span class="satellite-name">{{ satellite.name }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'DeviceQueryGantt',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    startDate: {
      type: String,
      default: ''
    },
    dayCount: {
      type: Number,
      default: 30
    }
  },
  data() {
    return {
      isScrollingFromSatelliteGrid: false,
      isScrollingFromTimeLabels: false,
      scheduleItems: [],
      satellites: [],
      availableDevices: { testCenter: [], assembly: [] },
      satelliteColorMap: {} // 卫星颜色映射
    }
  },
  computed: {
    // 生成时间槽
    timeSlots() {
      const slots = []
      const start = new Date(this.startDate)
      
      for (let i = 0; i < this.dayCount; i++) {
        const date = new Date(start)
        date.setDate(start.getDate() + i)
        slots.push({
          index: i,
          date: date,
          startDate: date
        })
      }
      
      return slots
    },

    // 获取所有设备列表（来自设备资源维护）
    allDevices() {
      const deviceList = []
      
      // 添加试验中心设备
      if (this.availableDevices.testCenter) {
        this.availableDevices.testCenter.forEach(device => {
          deviceList.push({
            name: device.name,
            category: '试验中心',
            quantity: device.quantity,
            capacity: device.capacity
          })
        })
      }
      
      // 添加总装&机构展开设备
      if (this.availableDevices.assembly) {
        this.availableDevices.assembly.forEach(device => {
          deviceList.push({
            name: device.name,
            category: '总装&机构展开',
            quantity: device.quantity,
            capacity: device.capacity
          })
        })
      }
      
      return deviceList
    },

    // 获取所有卫星的颜色映射 - 统一使用蓝色
    satelliteColors() {
      const blueColor = '#1976D2' // 统一使用蓝色
      const colorMap = {}
      this.satellites.forEach((satellite, index) => {
        colorMap[satellite.id] = blueColor
      })
      return colorMap
    }
  },
  watch: {
    // 监控组件显示状态，当显示时加载数据
    visible: {
      handler(newVal) {
        if (newVal) {
          this.loadAllData()
        }
      },
      immediate: true
    },
    
    // 监控 scheduleItems 变化，确保实时更新
    scheduleItems: {
      handler(newItems, oldItems) {
        // 数据变化时的处理逻辑
      },
      deep: true,
      immediate: false
    }
  },
  methods: {
    closeDeviceQuery() {
      this.$emit('close')
    },

    // 从数据库加载设备数据
    async loadDevices() {
      try {
        const response = await axios.get('/api/equipment/')
        if (response.data.success) {
          const devices = response.data.data
          
          // 按组织分类设备
          this.availableDevices = {
            testCenter: devices
              .filter(device => device.organization === '试验中心')
              .map(device => ({
                id: device.id,
                name: device.device_name,
                quantity: device.device_quantity,
                capacity: device.device_capacity
              })),
            assembly: devices
              .filter(device => device.organization === '总装&机构展开')
              .map(device => ({
                id: device.id,
                name: device.device_name,
                quantity: device.device_quantity,
                capacity: device.device_capacity
              }))
          }
        }
      } catch (error) {
        console.error('加载设备数据失败:', error)
      }
    },

    // 从数据库加载排程数据并解析设备使用信息
    async loadScheduleData() {
      try {
        const response = await axios.get('/api/scheduling/')
        
        // 处理不同的API响应格式
        let scheduleData = []
        if (Array.isArray(response.data)) {
          // 直接是数组格式
          scheduleData = response.data
        } else if (response.data && response.data['satellite-schedules']) {
          // 如果返回的是包含链接的对象，尝试获取具体的排程数据
          try {
            const satelliteSchedulesResponse = await axios.get(response.data['satellite-schedules'])
            if (Array.isArray(satelliteSchedulesResponse.data)) {
              scheduleData = satelliteSchedulesResponse.data
            } else if (satelliteSchedulesResponse.data && satelliteSchedulesResponse.data.results) {
              scheduleData = satelliteSchedulesResponse.data.results
            }
          } catch (error) {
            // 如果获取失败，返回空数组
            scheduleData = []
          }
        } else if (response.data && response.data.results && Array.isArray(response.data.results)) {
          // 分页格式
          scheduleData = response.data.results
        } else if (response.data && response.data.data && Array.isArray(response.data.data)) {
          // 封装格式
          scheduleData = response.data.data
        }
        
        if (Array.isArray(scheduleData) && scheduleData.length > 0) {
          this.scheduleItems = []
          this.satellites = []
          
          // 处理每个卫星的排程数据
          for (const schedule of scheduleData) {
            
            // 添加卫星信息
            if (schedule.satellite_info) {
              this.satellites.push({
                id: schedule.satellite,
                name: schedule.satellite_info.name,
                group: schedule.satellite_info.group,
                project: schedule.satellite_info.group?.project
              })
              
              // 为卫星生成颜色（统一使用蓝色）
              if (!this.satelliteColorMap[schedule.satellite]) {
                this.satelliteColorMap[schedule.satellite] = '#1976D2' // 统一使用蓝色
              }
            }
            
            // 直接从schedule_info中解析设备使用信息
            if (schedule.schedule_info) {
              // 尝试解析schedule_info（可能是字符串或对象）
              let scheduleData = schedule.schedule_info
              if (typeof scheduleData === 'string') {
                try {
                  scheduleData = JSON.parse(scheduleData)
                } catch (e) {
                  continue
                }
              }
              
              // 查找任务列表 - 尝试所有可能的字段名
              let tasks = []
              if (Array.isArray(scheduleData)) {
                tasks = scheduleData
              } else if (scheduleData && scheduleData.scheduleItems && Array.isArray(scheduleData.scheduleItems)) {
                tasks = scheduleData.scheduleItems
              } else if (scheduleData && scheduleData.tasks && Array.isArray(scheduleData.tasks)) {
                tasks = scheduleData.tasks
              } else if (scheduleData && scheduleData.items && Array.isArray(scheduleData.items)) {
                tasks = scheduleData.items
              }
              
              // 如果找不到任务，跳过此卫星
              if (tasks.length === 0) {
                continue
              }
              
              // 处理每个任务
              for (const task of tasks) {
                // 获取任务的基本信息
                const taskName = task.title || task.taskName || task.name || task.task_name || '未命名任务'
                const satelliteName = schedule.satellite_info?.name || `卫星${schedule.satellite}`
                
                // 获取任务的时间信息
                let startDay = 0
                if (task.startDay !== undefined && task.startDay !== null) {
                  startDay = task.startDay
                } else if (task.day !== undefined && task.day !== null) {
                  startDay = task.day
                } else if (task.startDate && this.startDate) {
                  const taskStart = new Date(task.startDate)
                  const queryStart = new Date(this.startDate)
                  startDay = Math.floor((taskStart - queryStart) / (24 * 60 * 60 * 1000))
                }
                
                // 获取任务持续时间
                const duration = task.duration || task.estimatedDuration || task.days || 1
                
                // 获取任务需要的设备
                let devices = []
                if (task.requiredDevices && Array.isArray(task.requiredDevices)) {
                  devices = task.requiredDevices
                } else if (task.requiredDevice) {
                  devices = [task.requiredDevice]
                } else if (task.devices && Array.isArray(task.devices)) {
                  devices = task.devices
                } else if (task.device) {
                  devices = [task.device]
                }
                
                // 如果有设备配置信息，按天处理
                if (task.dayConfigs && Array.isArray(task.dayConfigs)) {
                  for (let dayIndex = 0; dayIndex < task.dayConfigs.length; dayIndex++) {
                    const dayConfig = task.dayConfigs[dayIndex]
                    const timeIndex = startDay + dayIndex
                    
                    if (dayConfig && Array.isArray(dayConfig) && dayConfig.length > 0) {
                      // 使用当天配置的设备
                      for (const deviceName of dayConfig) {
                        this.scheduleItems.push({
                          satelliteId: schedule.satellite,
                          satelliteName: satelliteName,
                          taskName: taskName,
                          deviceName: deviceName,
                          timeIndex: timeIndex,
                          color: '#1976D2' // 统一使用蓝色
                        })
                      }
                    } else if (dayConfig === true && devices.length > 0) {
                      // 使用任务的默认设备
                      for (const deviceName of devices) {
                        this.scheduleItems.push({
                          satelliteId: schedule.satellite,
                          satelliteName: satelliteName,
                          taskName: taskName,
                          deviceName: deviceName,
                          timeIndex: timeIndex,
                          color: '#1976D2' // 统一使用蓝色
                        })
                      }
                    }
                  }
                } else if (devices.length > 0) {
                  // 如果没有dayConfigs，使用duration和devices创建记录
                  for (let i = 0; i < duration; i++) {
                    for (const deviceName of devices) {
                      this.scheduleItems.push({
                        satelliteId: schedule.satellite,
                        satelliteName: satelliteName,
                        taskName: taskName,
                        deviceName: deviceName,
                        timeIndex: startDay + i,
                        color: '#1976D2' // 统一使用蓝色
                      })
                    }
                  }
                }
              }
            }
          }
        } else {
          // 如果没有数据，初始化为空
          this.scheduleItems = []
          this.satellites = []
        }
      } catch (error) {
        console.error('加载排程数据失败:', error)
      }
    },

    // 加载所有数据
    async loadAllData() {
      if (!this.visible) return
      
      try {
        await Promise.all([
          this.loadDevices(),
          this.loadScheduleData()
        ])
      } catch (error) {
        console.error('加载数据失败:', error)
      }
    },

    formatTimeSlot(timeSlot) {
      const formatDate = (date) => {
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        return `${month}/${day}`
      }
      
      return formatDate(timeSlot.startDate)
    },

    // 获取指定设备在指定时间被哪些卫星使用
    getSatellitesUsingDevice(deviceName, timeIndex) {
      // 直接从设备使用记录中查找匹配的记录
      const deviceUsageRecords = this.scheduleItems.filter(item => {
        // 尝试多种匹配方式
        const exactMatch = item.deviceName === deviceName
        const trimmedMatch = item.deviceName && deviceName && 
          item.deviceName.trim() === deviceName.trim()
        const partialMatch = item.deviceName && deviceName && 
          (item.deviceName.includes(deviceName) || deviceName.includes(item.deviceName))
        
        return (exactMatch || trimmedMatch || partialMatch) && item.timeIndex === timeIndex
      })

      // 按卫星分组，合并同一卫星的多个任务
      const satelliteMap = new Map()
      
      deviceUsageRecords.forEach(record => {
        if (satelliteMap.has(record.satelliteId)) {
          // 如果卫星已存在，合并任务名称
          const existing = satelliteMap.get(record.satelliteId)
          if (!existing.taskName.includes(record.taskName)) {
            existing.taskName = existing.taskName ? `${existing.taskName}, ${record.taskName}` : record.taskName
          }
        } else {
          satelliteMap.set(record.satelliteId, {
            id: record.satelliteId,
            name: record.satelliteName,
            color: '#1976D2', // 统一使用蓝色
            taskName: record.taskName
          })
        }
      })
      
      return Array.from(satelliteMap.values())
    },

    // 获取卫星单元格的CSS类
    getSatelliteCellClass(deviceName, timeIndex) {
      const satellites = this.getSatellitesUsingDevice(deviceName, timeIndex)
      
      if (satellites.length === 0) {
        return 'empty-cell'
      } else if (satellites.length === 1) {
        return 'single-satellite-cell'
      } else {
        return 'multiple-satellite-cell'
      }
    },

    // 获取卫星单元格的提示信息
    getSatelliteCellTooltip(deviceName, timeIndex) {
      const satellites = this.getSatellitesUsingDevice(deviceName, timeIndex)
      
      if (satellites.length === 0) {
        return '此时间段该设备无使用'
      }
      
      const tooltipLines = satellites.map(satellite => {
        let line = `${satellite.name}`
        if (satellite.taskName) {
          line += ` - 任务: ${satellite.taskName}`
        }
        return line
      })
      
      return tooltipLines.join('\n')
    },

    // 处理卫星网格滚动，同步时间轴滚动
    onSatelliteGridScroll(event) {
      this.isScrollingFromSatelliteGrid = true
      if (this.$refs.timeLabels && !this.isScrollingFromTimeLabels) {
        this.$refs.timeLabels.scrollLeft = event.target.scrollLeft
      }
      this.$nextTick(() => {
        this.isScrollingFromSatelliteGrid = false
      })
    },

    // 处理时间轴滚动，同步卫星网格滚动
    onTimeLabelsScroll(event) {
      this.isScrollingFromTimeLabels = true
      if (this.$refs.satelliteGrid && !this.isScrollingFromSatelliteGrid) {
        this.$refs.satelliteGrid.scrollLeft = event.target.scrollLeft
      }
      this.$nextTick(() => {
        this.isScrollingFromTimeLabels = false
      })
    }
  }
}
</script>

<style scoped>
.device-query-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.device-query-modal {
  background: white;
  width: 95%;
  height: 90%;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.device-query-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
  background-color: #f8f9fa;
}

.device-query-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background-color: #e9ecef;
  color: #333;
}

.device-query-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 甘特图头部样式 */
.gantt-header {
  border-bottom: 2px solid #dee2e6;
  background-color: #f8f9fa;
}

.gantt-time-axis {
  display: flex;
}

.time-label-header {
  width: 100px;
  padding: 0;
  font-weight: bold;
  border-right: 1px solid #dee2e6;
  background-color: #e9ecef;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
  box-sizing: border-box;
}

.header-title {
  font-size: 13px;
  color: #495057;
  text-align: center;
  line-height: 1.2;
}

.time-labels {
  display: flex;
  flex: 1;
  overflow-x: auto;
}

.time-label {
  min-width: 60px;
  padding: 0;
  border-right: 1px solid #dee2e6;
  text-align: center;
  font-size: 11px;
  font-weight: 500;
  color: #495057;
  white-space: nowrap;
  height: 40px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 甘特图主体样式 */
.gantt-body {
  flex: 1;
  overflow: auto;
}

.gantt-devices {
  display: flex;
  min-height: 100%;
}

.device-labels {
  width: 100px;
  border-right: 2px solid #dee2e6;
  background-color: #f8f9fa;
}

.device-label {
  padding: 0 6px;
  border-bottom: 1px solid #dee2e6;
  font-weight: 500;
  color: #495057;
  display: flex;
  align-items: center;
  height: 40px;
  font-size: 12px;
  box-sizing: border-box;
  transition: all 0.2s ease;
  cursor: pointer;
}

.device-label:hover {
  background-color: #e9ecef;
  color: #007bff;
  font-weight: 600;
}

.satellite-grid {
  flex: 1;
  overflow-x: auto;
}

.device-row {
  display: flex;
  border-bottom: 1px solid #dee2e6;
  height: 40px;
  min-height: 40px; /* 确保最小高度 */
}

.satellite-cell {
  min-width: 60px;
  height: 40px;
  border-right: 1px solid #dee2e6;
  border-bottom: 1px solid #dee2e6;
  position: relative;
  background-color: #fff;
  box-sizing: border-box;
  transition: all 0.2s ease;
}

.satellite-cell:hover {
  background-color: #f0f8ff !important;
  border-color: #007bff;
  box-shadow: inset 0 0 0 1px #007bff;
}

.satellite-cell.empty-cell {
  background-color: #f8f9fa;
}

.satellite-cell.empty-cell:hover {
  background-color: #e9ecef !important;
}

.satellite-cell.single-satellite-cell {
  background-color: #e8f5e8;
}

.satellite-cell.single-satellite-cell:hover {
  background-color: #d4edda !important;
}

.satellite-cell.multiple-satellite-cell {
  background-color: #fff3cd;
}

.satellite-cell.multiple-satellite-cell:hover {
  background-color: #ffeaa7 !important;
}

.satellite-info {
  padding: 2px;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  gap: 1px;
  max-height: 36px; /* 限制最大高度，超出部分滚动 */
}

.satellite-item {
  padding: 1px 4px;
  border-radius: 2px;
  font-size: 10px;
  color: white;
  text-shadow: 0 1px 1px rgba(0,0,0,0.3);
  display: flex;
  align-items: center;
  justify-content: flex-start;
  min-height: 12px; /* 减小最小高度以容纳更多卫星 */
  max-height: 12px; /* 限制最大高度 */
  overflow: hidden;
  margin-bottom: 1px;
  flex-shrink: 0;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.satellite-item:hover {
  transform: scale(1.05);
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  filter: brightness(1.1);
}

.satellite-name {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
  transition: all 0.2s ease;
}

.satellite-item:hover .satellite-name {
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0,0,0,0.5);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .device-query-modal {
    width: 98%;
    height: 95%;
  }
  
  .time-label, .satellite-cell {
    min-width: 50px;
  }
  
  .device-labels {
    width: 60px;
  }
  
  .satellite-item {
    font-size: 9px;
  }
}

/* 滚动条样式 */
.gantt-body::-webkit-scrollbar,
.satellite-grid::-webkit-scrollbar,
.time-labels::-webkit-scrollbar,
.satellite-info::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.gantt-body::-webkit-scrollbar-track,
.satellite-grid::-webkit-scrollbar-track,
.time-labels::-webkit-scrollbar-track,
.satellite-info::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.gantt-body::-webkit-scrollbar-thumb,
.satellite-grid::-webkit-scrollbar-thumb,
.time-labels::-webkit-scrollbar-thumb,
.satellite-info::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.gantt-body::-webkit-scrollbar-thumb:hover,
.satellite-grid::-webkit-scrollbar-thumb:hover,
.time-labels::-webkit-scrollbar-thumb:hover,
.satellite-info::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 卫星信息区域的滚动条更细一些 */
.satellite-info::-webkit-scrollbar {
  width: 6px; /* 稍微增加宽度，让用户更容易注意到可以滚动 */
}

.satellite-info::-webkit-scrollbar-track {
  background: rgba(0,0,0,0.1);
  border-radius: 3px;
}

.satellite-info::-webkit-scrollbar-thumb {
  background: rgba(0,0,0,0.3);
  border-radius: 3px;
}

.satellite-info::-webkit-scrollbar-thumb:hover {
  background: rgba(0,0,0,0.5);
}
</style>
